<!--
 * @Author: your name
 * @Date: 2021-06-18 15:01:34
 * @LastEditTime: 2021-06-27 11:20:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \totiao\src\views\Login\Login.vue
-->
<template>
  <div class="login-container">
    <!-- 头部区域 -->
    <van-nav-bar title="黑马头条" fixed />
    <!-- 登录的表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        label="手机号码"
        placeholder="请填写手机号"
        required
        :rules="[
          { required: true },
          { pattern: /^1\d{10}$/, message: '请填写用户名' },
        ]"
      />
      <!-- :rules="[{ required: true, message: '请填写用户名' }]" -->
      <van-field
        v-model="form.code"
        type="password"
        name="密码"
        label="登录密码"
        placeholder="请填写密码"
        required
        :rules="[{ required: true }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 按需导入api接口
import { loginAPI } from '../../api/userApi'
import { mapMutations } from 'vuex'
export default {
  // 组件的name属性的值,首字母大写
  name: 'Login',
  data () {
    return {
      // 用户填写的表单数据
      form: {
        // 手机号
        mobile: '16984254461',
        // 密码
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    // 表单的提交事件
    async onSubmit () {
      // console.log('ok')
      // 1.获取到用户填写的登录信息对象
      console.log(this.form)
      // 2.封装并调用登录的api接口
      // 如果调用某个方法的返回值是promise对象,则可以在方法之前添加 await 关键字
      const { data: res } = await loginAPI(this.form)
      if (res.message === 'OK') {
        // 证明登录成功
        // // 1.把token保存
        // localStorage.setItem('token', JSON.stringify(res.data))
        // 把token信息存储到vuex中
        this.updateTokenInfo(res.data)
        // 2.跳转首页
        const navPath = this.$route.query.pre || '/'
        this.$router.replace(navPath)
      }
    }
  }
}
</script>

<style lang='less' scoped>
.login-container {
  padding-top: 46px;
}
</style>
